package com.wfs.suanfa.nio.demo.echo.server;

import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;

import java.net.InetSocketAddress;

/**
 * @author wfs
 * @date 2021/4/11 21:38
 */
public class EchoServer {
    private final int port;
    public EchoServer(int port){
        this.port=port;
    }
    public static void main(String[] args) {
        int port=9999;
        try {
            new EchoServer(port).start();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    private void start() throws InterruptedException {
        EchoServerHandler echoServerHandler=new EchoServerHandler();
        EventLoopGroup group=new NioEventLoopGroup();
        try {
        ServerBootstrap b=new ServerBootstrap();

        b.group(group)
                //指定所使用的的nio传输channel
                .channel(NioServerSocketChannel.class)
                .localAddress(new InetSocketAddress("localhost",port))
                .childHandler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        socketChannel.pipeline().addLast(echoServerHandler);
                    }
                });
        //异步地绑定服务器，调用sync()方法阻塞等待直接绑定完成
        ChannelFuture f = b.bind().sync();
            //获取channel的closeFuture 并且阻塞当前线程直接到它完成
            f.channel().closeFuture().sync();
        }finally {
            group.shutdownGracefully().sync();
        }

    }
}
